package com.codecash.service.impl;

import com.codecash.entity.FeedBack;
import com.codecash.mapper.UserMapper;
import com.codecash.entity.User;
import com.codecash.service.UserService;
import com.codecash.util.Md5Util;
import com.codecash.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceimpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public void register(String username, String password, String email) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        //添加
        userMapper.add(username,md5String,email);
    }

    @Override
    public void updatePartial(Integer userId, String username, String email) {
        // 检查是否存在重复的用户名
        int count = userMapper.countByUsername(username, userId);
        if (count > 0) {
            throw new RuntimeException("用户名已存在，请选择不同的用户名");
        }
        // 仅更新 username 和 email
        userMapper.updatePartial(username, email, userId);
    }

    @Override
    public void addCall(FeedBack feedBack) {
        feedBack.setCreateTime(LocalDateTime.now()); // 设置创建时间
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id"); // 获取当前用户ID
        feedBack.setUserId(id); // 将用户ID设置到 FeedBack 对象
        userMapper.addCall(feedBack); // 直接调用 Mapper
    }



    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id") ;
        userMapper.updateAvatar(avatarUrl,id);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id") ;
        userMapper.updatePwd(Md5Util.getMD5String(newPwd),id);
    }

    @Override
    public User findByEmail(String email) {
        User u = userMapper.findByEmail(email);
        return u;
    }
}